package ai;

import handlers.NonAvatarMvtHandler;
import map.Direction;
import scheduler.DuplicateEventException;
import scheduler.Scheduler;
import entity.Entity;

public class WorldAI extends AI {

	private Scheduler scheduler;
	private int speed;
	
	public WorldAI() {
	//	enemies = new HashMap<Entity,Notifiable>();
		scheduler = Scheduler.getInstance();
		speed = 50;
	}
	
	public boolean addEntity(Entity entity) {
		try {
			WorldBrain brain = new WorldBrain(entity);
			getEnemies().put(entity,brain);
			scheduler.schedule(brain, speed);
			return true;
		}
		catch(DuplicateEventException dee) {
			System.out.println(dee.toString());
			return false;
		}
		
	}
	
	public void removeEntity(Entity entity) {
		scheduler.cancel(getEnemies().remove(entity));
	}
	
	public void removeAll() {
		for(Entity e : getEnemies().keySet()) {
			removeEntity(e);
		}
	}
	/**
	 * Inner class in charge of running each enemies individually
	 * @author clopez
	 *
	 */
	private class WorldBrain extends Brain {	
		
		public WorldBrain(Entity e) {
			move =  new NonAvatarMvtHandler(e);
		}

		@Override
		public void execute() {
			if(decMaintain()) {
				maintain = ranGen.nextInt(duration);
				dir = Direction.getRandomDir();
			}
			else {
				if(!move.move(dir)) {
					dir = Direction.getRandomDir();
					execute();
				}
			}	
		}
		public boolean decMaintain() {
			if (maintain-- <= 0) 
				return true;
			return false;
		}

	}
	
}
